package com.jiukuaidao.zhulin.module.home;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiukuaidao.library.Config;
import com.jiukuaidao.library.base.BaseFragment;
import com.jiukuaidao.library.base.BaseHolder;
import com.jiukuaidao.library.base.BaseRecyclerViewAdapter;
import com.jiukuaidao.library.base.BaseXrecyclerViewAdapter;
import com.jiukuaidao.library.util.ImageGlideUtils;
import com.jiukuaidao.library.util.LogUtil;
import com.jiukuaidao.library.widget.banner.ConvenientBanner;
import com.jiukuaidao.library.widget.banner.listener.OnItemClickListener;
import com.jiukuaidao.library.widget.recyclerview.XRecyclerView;
import com.jiukuaidao.library.widget.recyclerview.ref.impl.header1.AVLoadingIndicatorView;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiGeoCoderInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo;
import com.jiukuaidao.zhulin.entity.ApiHomeAds;
import com.jiukuaidao.zhulin.entity.ApiHomePros;
import com.jiukuaidao.zhulin.entity.EventShopInfo;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.address.ChangePositionActivity;
import com.jiukuaidao.zhulin.module.commodity.GoodsDetailActivity;
import com.jiukuaidao.zhulin.module.home.contract.HomeContract;
import com.jiukuaidao.zhulin.module.home.presenter.HomePresenter;
import com.jiukuaidao.zhulin.util.AddressInfoUtil;
import com.jiukuaidao.zhulin.util.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author : H_Joker
 * Date : 2016/5/27
 * Description : 首页
 */
public class HomeFragment extends BaseFragment<HomeContract.Presenter> implements HomeContract.View, XRecyclerView.OnRefreshListener, CommContract.ShoppingCartLocalView {

    @BindView(R.id.delivery)
    TextView delivery;
    @BindView(R.id.title_center_text)
    TextView titleCenterText;
    @BindView(R.id.load_progress)
    AVLoadingIndicatorView loadProgress;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.xrl_products)
    XRecyclerView mRlPros;
    private RecyclerView mRlActs;
    private ConvenientBanner mCbBanner;
    private LinearLayout mNoProLayout;
    private BaseXrecyclerViewAdapter mProListAdapter;
    private BaseRecyclerViewAdapter mActListAdapter;

    private String mCityId = "131";
    private String mLongitude = "116.571789";
    private String mLatitude = "39.795832";

    private CommPresenter mCommPresenter;
    /**
     * 可为定位到的城市，也可是切换的城市
     */
    private String mCityCode;
    private String mCurrentCity;

    /**
     * 当前加减购物车的商品货号
     */
    private String mCurProNumber;
    /**
     * 当前加减购物车的商品价格
     */
    private String mCurProPrice;

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        initRecyclerView();
        onRefresh();
        if (!StringUtils.isEmpty(AddressInfoUtil.getAddressInfo().address)) {
            titleCenterText.setText(AddressInfoUtil.getAddressInfo().address);
        } else {
            titleCenterText.setText(getString(R.string.location_err));
        }
    }

    @Override
    protected void bindMVP() {
        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(getActivity()), this);
        mCommPresenter.getShoppingCartDataLocal();
        new HomePresenter(TaskProvider.provideHomeRepository(Config.mContext), this);
    }

    private void initRecyclerView() {

        GridLayoutManager layoutManager = new GridLayoutManager(Config.mContext, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mProListAdapter = new BaseXrecyclerViewAdapter<ApiHomePros.ApiHomeProItem>(Config.mContext, R.layout.item_home_goodslist, mPresenter.getProList(), mRlPros) {
            @Override
            public void updateUI(BaseHolder holder, int position, ApiHomePros.ApiHomeProItem data) {
                ImageGlideUtils.GlideImages(HomeFragment.this, data.uri, (ImageView) holder.getView(R.id.img_product), R.mipmap.ic_launcher);
                ((TextView) holder.getView(R.id.tv_proName)).setText(data.name);
                ((TextView) holder.getView(R.id.price_product)).setText("￥" + data.retailPrice);

                // 购物车中数量
                String proNumber = data.number;
                List<EventShoppingCartInfo> shoppingCart = mPresenter.getShoppingCart();
                int count = 0;
                if (shoppingCart != null) {
                    for (EventShoppingCartInfo item : shoppingCart) {
                        if (proNumber.equals(item.getGoodsGN())) {// 如果数据库中有此商品
                            count = item.getCount();
                            break;
                        }
                    }
                }
                if (count <= 0) {// 购物车中没有此商品
                    holder.getView(R.id.add_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.reduce_good_image).setVisibility(View.GONE);
                    holder.getView(R.id.current_good_count).setVisibility(View.GONE);
                } else {// 购物车中有此商品
                    holder.getView(R.id.add_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.reduce_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.current_good_count).setVisibility(View.VISIBLE);
                    ((TextView) holder.getView(R.id.current_good_count)).setText("" + count);

                }
            }

            @Override
            protected void setTouchListener(final BaseHolder holder, final int position) {
                super.setTouchListener(holder, position);

                // 购物车增加商品
                holder.getView(R.id.add_good_image).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCurProNumber = mPresenter.getProList().get(position).number;
                        mCurProPrice = mPresenter.getProList().get(position).retailPrice;
                        mCommPresenter.addShoppingCartLocal();
                    }
                });

                // 购物车减少商品
                holder.getView(R.id.reduce_good_image).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCurProNumber = mPresenter.getProList().get(position).number;
                        mCurProPrice = mPresenter.getProList().get(position).retailPrice;
                        mCommPresenter.reduceShoppingCartLocal();
                    }
                });
            }

            @Override
            protected void onItemClick(BaseHolder holder, int position) {
                super.onItemClick(holder, position);

                // 跳转至商品详情
                String proId = mPresenter.getProList().get(position).id;
                String deliveryLimit = String.valueOf(mPresenter.getShopInfo().deliveryLimit);
                String deliveryFull = mPresenter.getShopInfo().deliveryPrice;
                Bundle bundle = new Bundle();
                bundle.putString("goodsId", proId);
                bundle.putString("startPrice", deliveryLimit);
                bundle.putString("fullShipmentFree",deliveryFull);
                intentJump(GoodsDetailActivity.class, bundle);
            }
        };

        mRlPros.setLayoutManager(layoutManager);
        mRlPros.setAdapter(mProListAdapter);
        mRlPros.setOnRefreshListener(this);

        initHeader();

    }

    private void initHeader() {
        View header = View.inflate(Config.mContext, R.layout.header_home_list, null);

        mRlActs = (RecyclerView) header.findViewById(R.id.rcl_ad);
        mCbBanner = (ConvenientBanner) header.findViewById(R.id.cb_banner);
        mNoProLayout = (LinearLayout) header.findViewById(R.id.product_null_ll);

        refreshBannerUi(null, null);
        initActs();

        mRlPros.addHeaderView(header);
    }

    private void initActs() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(Config.mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRlActs.setLayoutManager(layoutManager);
        mActListAdapter = new BaseRecyclerViewAdapter<ApiHomeAds.ApiHomeActItem>(Config.mContext, R.layout.item_home_adlist, mPresenter.getActList(), mRlActs) {
            @Override
            public void updateUI(BaseHolder holder, int position, ApiHomeAds.ApiHomeActItem data) {
                ImageGlideUtils.GlideImages(HomeFragment.this, data.pictureUri, (ImageView) holder.getView(R.id.iv_ad), R.mipmap.ic_launcher);
            }

            @Override
            protected void onItemClick(BaseHolder holder, int position) {
                super.onItemClick(holder, position);
                // TODO 点击运营位

            }
        };
        mRlActs.setAdapter(mActListAdapter);
    }

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected void onUserVisible() {
    }

    @Override
    protected void onUserInvisible() {

    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onRefresh() {
        String cityCode = AddressInfoUtil.getAddressInfo().cityCode;
        String latitude = AddressInfoUtil.getAddressInfo().latitude;
        String longitude = AddressInfoUtil.getAddressInfo().longitude;
        mPresenter.refreshAdsAndAct(cityCode);
        mPresenter.loadPros(HomeContract.REFRESH, 1, null, cityCode, longitude, latitude);
    }

    @Override
    public void onLoadMore() {
        String cityCode = AddressInfoUtil.getAddressInfo().cityCode;
        String latitude = AddressInfoUtil.getAddressInfo().latitude;
        String longitude = AddressInfoUtil.getAddressInfo().longitude;
        mPresenter.loadPros(HomeContract.LOADMORE, mPresenter.getCurPageIndex() + 1, null, cityCode, longitude, latitude);
    }

    @Override
    public void refreshBannerUi(List<String> imgs, final List<ApiHomeAds.ApiHomeAdItem> adList) {
        if (mCbBanner.getAdapter() == null) {
            mCbBanner.setPages(imgs, R.mipmap.ic_home_lbs_ac_bg).setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    // TODO 处理banner轮播图中的图片点击事件
                    if (adList != null && !adList.isEmpty()) {

                    }
                }
            }).setPageIndicator(new int[]{R.mipmap.page_indicator_white, R.mipmap.page_indicator_focused_red});
        } else {
            mCbBanner.notifyDataSetChanged();
        }
        if (imgs != null) {
            mCbBanner.setCanLoop(imgs.size() > 1);
        } else {
            mCbBanner.setCanLoop(false);
        }
    }

    @Override
    public void refreshActsUi(List<ApiHomeAds.ApiHomeActItem> acts) {
        mActListAdapter.setData(acts);
        mActListAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshProsUi(List<ApiHomePros.ApiHomeProItem> pros) {
        mProListAdapter.setData(pros);
        mProListAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadComplete(int act, boolean isOver, boolean isEmpty) {

        LogUtil.log("act：" + act + " isOver:" + isOver + " isEmpty" + isEmpty);

        if (act == HomeContract.REFRESH) {
            mRlPros.refreshComplete();
        } else {
            mRlPros.loadMoreComplete();
        }
        if (isOver) {
            mRlPros.loadNoMore();
        }
        if (isEmpty) {
            mNoProLayout.setVisibility(View.VISIBLE);
        } else {
            mNoProLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void refreshShopInfoUI(ApiHomePros.ApiHomeShop shopInfo) {
        EventShopInfo info = new EventShopInfo();
        info.setDeliveryLimit(String.valueOf(shopInfo.deliveryLimit));
        EventBus.getDefault().post(info);
    }

    /**
     * 跳转至切换地址
     */
    @OnClick(R.id.title_center_text)
    public void changeLocation() {
        Bundle bundle = new Bundle();
        bundle.putString("cityCode", mCityCode);
        bundle.putString("city", mCurrentCity);
        intentJump(ChangePositionActivity.class, bundle);
    }

    /**
     * 定位当前位置 接收的地址
     *
     * @param apiGeoCoderInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventLocationResult(ApiGeoCoderInfo apiGeoCoderInfo) {
        titleCenterText.setText(apiGeoCoderInfo.result.sematic_description);
        mCityCode = apiGeoCoderInfo.result.cityCode;
        mCurrentCity = apiGeoCoderInfo.result.addressComponent.city;
        onRefresh();

    }

    /**
     * 地址切换 点击用户收货地址 接收的地址
     *
     * @param data
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUserAddress(ApiHistoryAddressInfo.AddressInfo data) {
        titleCenterText.setText(data.address);
        mCityCode = data.baiduCityCode;
        mCurrentCity = data.city;
        onRefresh();
    }

    /**
     * 购物车改变
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventShopingCart(List<EventShoppingCartInfo> datas) {
        mPresenter.setShoppingCart(datas);
        mProListAdapter.notifyDataSetChanged();
    }

    /**
     * 地址切换 点击搜索地址 接收的地址
     *
     * @param map
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPlace(Map<String, String> map) {
        titleCenterText.setText(map.get("name"));
        mCityCode = map.get("cityCode");
        mCurrentCity = map.get("city");
        onRefresh();
    }

    @Override
    public String getGoodsNumber() {
        return mCurProNumber;
    }

    @Override
    public String getGoodsCurPrice() {
        return mCurProPrice;
    }
}